package cjyyp.day04;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.*;


public class jdk线程池实战 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(20);
        Callable<Integer> task1=new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                int num=0;
                for (int i=1;i<100;i++){
                    num+=i;
                }
                return num;
            }
        };
        Callable<Integer> task2=new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                int num=0;
                for (int i=100;i<200;i++){
                    num+=i;
                }
                return num;
            }
        };
        Callable<Integer> task3=new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                int num=0;
                for (int i=200;i<300;i++){
                    num+=i;
                }
                return num;
            }
        };
        //提交批量任务
        List<Callable<Integer>> tasks= Arrays.asList(task1,task2,task3);
        List<Future<Integer>> futures = executorService.invokeAll(tasks);
        //单线程计算num
        int num=0;
        for (int i=1;i<300;i++){
            num+=i;
        }
        System.out.println("单线程num="+num);
        int num2=0;
        for (Future<Integer> future:futures){
            num2+=future.get();
        }
        //关闭线程池
        executorService.shutdown();
        System.out.println("多线程num="+num2);

    }
}
